<template>
  <view class="chat-container">
    <e-navbar :leftTitle="title"></e-navbar>
    <scroll-view
        class="chat-content"
        scroll-y
        :scroll-with-animation="scrollAnimation"
        :scroll-into-view="scrollToView"
        :scroll-top="scrollTop"
        :style="{'height':scrollHeight + 'px'}"
    >
      <view v-if="ai_id == 0" class="chat-color-bg"></view>
      <image v-else class="chat-bg" :src="$image('/images/ai-chat-bg' + ai_id + '.png')" mode="scaleToFill"></image>
      <template v-if="chatList.length <= 0">
        <view class="rela" style="z-index: 1;">
          <u-gap height="15"></u-gap>
          <view class="ai-avatar">
            <u-avatar :src="$image('/images/ai-avatar' + ai_id + '.png')" size="78"></u-avatar>
          </view>
          <view class="tips-card">
            <view v-html="tipsContnt"></view>
          </view>
          <view class="common-title flex col-center row-between">
            <view class="font-32 pingfang-heavy">常见问题</view>
            <view class="change-btn" @click="handleChangeFaq()">换一批</view>
          </view>
        </view>
        <view
          v-for="(item,index) in faqList"
          :key="index"
          class="hidefaq faq-item"
          :class="{'animation-slide-right showfaq':item.show && showFaq}"
          @click="handleFaqItem(item)"
        >{{item.title}}</view>
      </template>
      <template v-else>
        <!--    消息列表    -->
        <view class="msg-list">
          <u-gap height="20"></u-gap>
          <block v-for="(item,index) in chatList" :key="index" :id="'msg'+item.msg_id">
            <!--    用户每条消息      -->
            <view v-if="item.type == 'user'" class="msg-item user-msg-row">
              <view class="msg-avatar">
                <u-avatar :src="item.avatar" size="58"></u-avatar>
              </view>
              <view class="msg-content">
                <view v-html="item.message"></view>
              </view>
            </view>
            <!--    ai每条消息      -->
            <view v-if="item.type == 'ai'" class="msg-item ai-msg-row">
              <view class="msg-avatar">
                <u-avatar :src="item.avatar" size="58"></u-avatar>
              </view>
              <view class="msg-content">
                <view v-html="item.message"></view>
              </view>
            </view>
          </block>
        </view>
        <u-gap height="15"></u-gap>

      </template>
      <view class="bottom-content flex col-center row-between">
        <view class="bottom-content_input flex-1">
          <u-input v-model="inputValue" border="none" placeholder="有什么问题尽管问我" placeholder-style="color: #999999;"></u-input>
          <image class="send-icon" :src="$image('/images/send-btn.png')" mode="aspectFill" @click="handleSend()"></image>
        </view>
<!--        <view class="more-icon">
          <image :src="$image('/images/chat-more.png')" mode="aspectFill"></image>
        </view> -->
      </view>
      <u-gap height="100"></u-gap>
    </scroll-view>
  </view>
</template>

<script>
let app = getApp();
import { agent_chat } from "@/common/mock";
import {req_chat} from "../../../common/api";
import {getCalendarDate, getAiZangGan} from "@/common/utils";

export default {
  data() {
    return {
      title: "",
      scrollHeight: 0,
      ai_id: 1, // 占卜id
      // tipsContnt:`
      //   <p class="pingfang-heavy">亲爱的朋友，我是你的易经智慧助手，易小语~ 每天有什么困惑，都可以问问我，我来帮你卜一卦， 避避坑~ </p>
      //   <p>作为新朋友，你可以这样问我:</p>
      //   <p class="pingfang-heavy">"今天有客戶上门谈合作，我应该注意些什么?"</p>
      //   <p>好啦，开始向我提问吧~</p>
      // `,
      tipsContnt: "",
      faqList: [],
      showFaq: false,
      inputValue: "",
      requestAi_id:0, // 请求的ai Id
      chatList:[], //聊天列表
      scrollTop:0.01, //滚动条位置
      scrollAnimation: false, //滚动条动画
      scrollToView: "", //滚动条滚动到哪个元素位置
      userinfo:{},
      faqType:"", // ai快捷提问类型
      allFaqList:[],
      agent_chat: JSON.parse(JSON.stringify(agent_chat)),
      msgLoad: false,
    };
  },
  onLoad(options) {
    if(options.aiData){
      const aiData = JSON.parse(decodeURIComponent(options.aiData));
      console.log("灌灌灌灌", aiData);
      let { id, title, type, description } = aiData;
      if(description){
        this.tipsContnt = description;
      }
      if(title){
        this.title = decodeURIComponent(title);
      }
      if(type){
        this.faqType = type;
      }
      /*
        传入的id
        1=姻缘,2=事业,3=学业,4=健康,5=起名
        接口id
        0=通用,1=健康,2=学业,3=事业,4=解梦,5=姻缘,6=时运
      */
      if(id !== undefined || id !== null){
        this.ai_id = Number(id)
        this.requestAi_id = this.getRequestId(this.ai_id);
      }
    }
    this.getUserInfo();
  },
  onReady() {
    this.getElInfo();
    this.getFaqList();
    setTimeout(()=>{
      this.goTop();
    },1000);
  },
  methods: {
    getUserInfo(){
      app.getMineInfo().then(async (res)=>{
        this.userinfo = res;
        app.isCompleteInfo();
        if(this.userinfo){
          let calendarData = await getCalendarDate({
						date:this.$u.timeFormat(this.userinfo.birthday, "yyyy-mm-dd hh:MM:ss"),
            shenShaParams: {
              // isShenSha: true,
              day: this.$u.timeFormat(this.userinfo.birthday, "yyyy-mm-dd hh:MM:ss"),
              sex: this.userinfo.gender == "男" ? 1 : 0,
              name: this.userinfo.nickname,
            }
					});
          let {
            lunarDateChinese,
            shiShen,
            zangGan,
            naYin,
            kongWang,
            daYun,
            liuNian,
            jiShenXiongSha,
            aiZangGan
          } = calendarData;
          let bazi = {
            profile: {
              "姓名": this.userinfo.nickname,
              "性别": this.userinfo.gender,
            },
            "公历": this.$u.timeFormat(this.userinfo.birthday, "yyyy-mm-dd hh:MM:ss"),
            "农历": lunarDateChinese,
            "十神": shiShen,
            "纳音": naYin,
            "空亡": kongWang,
            "大运": daYun,
            "流年": liuNian.allData,
            "吉神凶煞": jiShenXiongSha,
            "藏干": aiZangGan,
          };
          let newBazi = Object.assign(this.agent_chat.bazi, bazi);
          this.agent_chat.birthday = this.$u.timeFormat(this.userinfo.birthday, 'yyyy-mm-dd');
          setTimeout(()=>{
            this.agent_chat.bazi = JSON.stringify(newBazi);
          },100)
        }
      });
    },
    // 发送消息之前先判断是否能进行发送
    async handleBeforeSend(value){
      let data = {
        "question": value,
        "answer": value
      };
      const res = await this.$api.is_allow(data);
      if(res.code == 1){
        return res;
      }
    },
    // 发送消息
    async handleSend(){
      console.log("查看发送状态", this.msgLoad);
      if(this.msgLoad) return this.$u.toast("ai正在回复中");
      if(!this.inputValue) return this.$u.toast("请输入咨询的问题");
      this.msgLoad = true;
      // 判断是否使用完次数
      let beforeData = await this.handleBeforeSend(this.inputValue);
      let { data, message } = beforeData;
      if(!data) return this.$u.toast(message);
      let params = {
        agent_type: this.requestAi_id,
        query: this.inputValue,
        // isAi: true,
      };
      // 是否占卜助手
      if(this.ai_id == 0){
        this.agent_chat.request_time = "";
        this.agent_chat.birthday = "";
        this.agent_chat.bazi = "{}";
        this.agent_chat.message_type = "";
      }else{
        this.agent_chat.request_time = uni.$u.timeFormat(new Date().getTime(), "yyyy-mm-dd hh:MM:ss");
      }
      const res = await this.$api.req_chat({...this.agent_chat, ...params});
      if(res.code == 1){
      // if(res.result !== "" && res.status == "SUCCESS"){
        let user_msg_id = this.$u.guid(5);
        // 添加用户信息
        let userParams = {
          type: 'user',
          avatar: this.$image(this.userinfo.avatar, 'yes'),
          message: this.inputValue,
          time: this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd' + ' ' + 'hh:MM:ss'),
          msg_id: user_msg_id,
        };

        // 添加用户消息到 chatList
        this.chatList.push(userParams);
        this.inputValue = "";
        this.goTop();
        this.scrollToView = user_msg_id;
        // 显示加载动画
        uni.showLoading({
          title: "请稍后",
        });
        // 延迟 2 秒模拟获取 AI 回复
        setTimeout(() => {
          uni.hideLoading();
          let ai_msg_id = this.$u.guid(5);
          // 初始化 aiParams 信息
          let aiParams = {
            type: 'ai',
            avatar: this.$image('/images/ai-avatar' + this.ai_id + '.png'),
            message: '', // 空字符串，逐字更新
            time: this.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd' + ' ' + 'hh:MM:ss'),
            msg_id: ai_msg_id,
          };
					
          // 添加空的 AI 回复到 chatList 中
          this.chatList.push(aiParams);
					
          let aiMessage = res.data.result;
          let index = 0;

          // 递归函数逐字更新 message
          const typeWriterEffect = () => {
            if (index < aiMessage.length) {
              // 直接修改 chatList 中最后一条消息的 message
              this.chatList[this.chatList.length - 1].message += aiMessage.charAt(index);
              index++;
              this.$nextTick(() => {
                // 使用 $forceUpdate 确保界面刷新
                this.$forceUpdate();
                this.goTop();
                // console.log(this.scrollTop);
                setTimeout(typeWriterEffect, 10); // 调整速度
              });
            }else{
              this.msgLoad = false;
              // 如果需要，触发其他操作或事件
              console.log("打字机效果完成，状态更新完成");
            }
          };
          this.scrollToView = ai_msg_id;
          typeWriterEffect();
        }, 1000);
      }
    },
    goTop() {
      // 解决view层不同步的问题
      this.$nextTick(function() {
        this.scrollTop = Math.floor(Math.random() * (999999999 - 111111111 + 1)) + 111111111;        this.scrollTop = Math.floor(Math.random() * (999999999 - 111111111 + 1)) + 111111111;
        // this.scrollTop = 999999999999;
      });
    },
    handleFaqItem(item){
      this.inputValue = item.title;
      this.handleSend();
    },
    async getElInfo() {
      let systemInfo = this.$u.sys();
      let rectInfo = await this.$u.getRect('.chat-content');
      this.scrollHeight = systemInfo.windowHeight - rectInfo.top;
    },
    // 获取需要请求的ai的id
    getRequestId(optId){
      switch(optId){
        case 1: //对应姻缘
          return 5;
        case 2: //对应事业
          return 3;
        case 3: //对应学业
          return 2;
        case 4: //对应健康
          return 1;
        case 5: //对应解梦
          return 4;
        default: //默认通用
          return 0;
      }
    },
    getFaqList(){
      setTimeout(()=>{
        this.animationFaq();
        this.showFaq = true;
      }, 300)
    },
    animationFaq(){
      // this.faqList = [
      //   {
      //     title: "今后三个月会不会涨工资？",
      //     show: false,
      //   },
      //   {
      //     title: "今后三个月会不会涨工资？",
      //     show: false,
      //   },
      //   {
      //     title: "今后三个月会不会涨工资？",
      //     show: false,
      //   },
      //   {
      //     title: "今后三个月会不会涨工资？",
      //     show: false,
      //   }
      // ];
      if(this.allFaqList.length == 0){
        let setting = uni.getStorageSync("setting");
        if(setting){
          setting = JSON.parse(setting);
          this.allFaqList = setting.filter(item => item.type == this.faqType);
        }
      }
      this.allFaqList.map((item,index)=>{
        this.$set(item, 'show', false);
        this.$set(item, 'title', item.text);
      })
      this.faqList = this.getRandomItemsWithDuplicates(this.allFaqList);
      console.log(this.faqList)
      this.faqList.map((item,index)=>{
        setTimeout(()=>{
          item.show = true;
        } ,index * 50);
      })
    },
    getRandomItemsWithDuplicates(array) {
      // 如果数组少于 5 条，直接返回整个数组
      if (array.length <= 5) {
        return array;
      }
      const result = [];
      for (let i = 0; i < 5; i++) {
        const randomIndex = Math.floor(Math.random() * array.length);
        result.push(array[randomIndex]);
      }
      return result;
    },
    // 点击换一批
    handleChangeFaq(){
      this.showFaq = false;
      this.faqList = [];
      this.getFaqList();
    }
  }
}
</script>
<style lang="scss" scoped>
  .chat-container{
    .chat-content{
      position: relative;
      z-index: 8;
      .chat-bg,.chat-color-bg{
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
      }
      .chat-color-bg{
        background: linear-gradient(180deg, #CDD4FF 0%, #EEF0FF 100%);
      }
      .ai-avatar{
        margin: 0 30rpx;
      }
      .tips-card{
        margin: 30rpx;
        padding: 30rpx;
        background: #fff;
        box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0,0,0,0.04);
        border-radius: 0rpx 20rpx 20rpx 40rpx;
        line-height: 52rpx !important;
        font-size: 28rpx !important;
      }
      .common-title{
        margin: 30rpx;
        .change-btn{
          font-size: 24rpx;
          color: #999;
          background: #fff;
          border-radius: 60rpx;
          padding: 6rpx 16rpx;
        }
      }
      .hidefaq{
        opacity: 0;
      }
      .showfaq{
        opacity: 1 !important;
      }
      .faq-item{
        margin: 16rpx 30rpx;
        background: #fff;
        box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0,0,0,0.04);
        border-radius: 0rpx 20rpx 20rpx 40rpx;
        font-size: 26rpx;
        padding: 20rpx 40rpx;
      }
      .bottom-content{
        position: fixed;
        bottom: 30rpx;
        width: 100%;
        padding-left: 30rpx;
        padding-right: 30rpx;
        z-index: 10;
        &_input{
          background: #FFFFFF;
          box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0,0,0,0.04);
          border-radius: 60rpx;
          padding: 10rpx 10rpx 10rpx 20rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .send-icon{
            width: 68rpx;
            height: 68rpx;
            display: block;
          }
        }
        .more-icon{
          image{
            width: 128rpx;
            height: 128rpx;
            display: block;
          }
        }
      }
      .msg-list{
        position: relative;
        .msg-item{
          padding: 0 30rpx;
          margin-bottom: 20rpx;
        }
        .user-msg-row{
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          .msg-avatar{
            .u-avatar{
              margin-left: auto;
            }
          }
          .msg-content{
            display: inline-block;
            width: auto;
            max-width: 80%;
            background: #fff;
            margin-left: auto;
            margin-top: 20rpx;
            border-radius: 14rpx;
            padding: 14rpx;
          }
        }
        .ai-msg-row{
          .msg-content{
            display: inline-block;
            width: auto;
            max-width: 80%;
            background: #fff;
            margin-top: 20rpx;
            border-radius: 14rpx;
            padding: 14rpx;
						view{
							white-space: pre-line;
						}
          }
        }
      }
    }
  }
</style>
